import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Paper,
  Typography,
  Button,
  TextField,
  IconButton,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Switch,
  FormControlLabel,
  Divider,
  Tooltip,

  CircularProgress,
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  PlayArrow as ConnectIcon,
  Stop as DisconnectIcon,
  Search as SearchIcon,
  Visibility as VisibilityIcon,
  VisibilityOff as VisibilityOffIcon,
  Computer as ComputerIcon,
  Key as KeyIcon,
  Lock as LockIcon,
} from '@mui/icons-material';
import { invoke } from '@tauri-apps/api/core';
import toast from 'react-hot-toast';

// Store
import { useAppStore } from '../store/appStore';

// Types
import type { ConnectionConfig, SshConfig } from '../types/config';
import type { SshConnection } from '../types/ssh';

const ConnectionManager: React.FC = () => {
  const navigate = useNavigate();
  const {
    connections,
    setConnections,
    addConnection,
    updateConnection,
    removeConnection,
    activeConnections,
    addActiveConnection,
    removeActiveConnection,
    searchQuery,
    setSearchQuery,
    connectionFilter,
    setConnectionFilter,
  } = useAppStore();

  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingConnection, setEditingConnection] = useState<ConnectionConfig | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showPrivateKeyPassphrase, setShowPrivateKeyPassphrase] = useState(false);
  const [formData, setFormData] = useState<Partial<ConnectionConfig>>({
    name: '',
    ssh_config: {
      host: '',
      port: 22,
      username: 'root',
      auth_method: { type: 'password' },
      password: '123456',
      private_key_path: '',
      private_key_passphrase: '',
      use_agent: false,
      connect_timeout: 30,
      keepalive_interval: 60,
      compression: true,
    },
    tunnels: [],
    tags: [],
    notes: '',
  });

  // 过滤连接列表
  const filteredConnections = connections.filter(connection => {
    const matchesSearch = connection.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         connection.ssh_config.host.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         connection.ssh_config.username.toLowerCase().includes(searchQuery.toLowerCase());
    
    if (!matchesSearch) return false;

    const activeConnection = activeConnections.find(ac => ac.id === connection.id);
    const isConnected = activeConnection?.status.status === 'connected';

    switch (connectionFilter) {
      case 'connected':
        return isConnected;
      case 'disconnected':
        return !isConnected;
      default:
        return true;
    }
  });

  // 打开新建/编辑对话框
  const handleOpenDialog = (connection?: ConnectionConfig) => {
    if (connection) {
      setEditingConnection(connection);
      setFormData(connection);
    } else {
      setEditingConnection(null);
      setFormData({
        name: '',
        ssh_config: {
          host: '',
          port: 22,
          username: 'root',
          auth_method: { type: 'password' },
          password: '123456',
          private_key_path: '',
          private_key_passphrase: '',
          use_agent: false,
          connect_timeout: 30,
          keepalive_interval: 60,
          compression: true,
        },
        tunnels: [],
        tags: [],
        notes: '',
      });
    }
    setIsDialogOpen(true);
  };

  // 关闭对话框
  const handleCloseDialog = () => {
    setIsDialogOpen(false);
    setEditingConnection(null);
    setFormData({});
    setShowPassword(false);
    setShowPrivateKeyPassphrase(false);
  };

  // 保存连接配置
  const handleSaveConnection = async () => {
    if (!formData.name || !formData.ssh_config?.host || !formData.ssh_config?.username) {
      toast.error('请填写必要的连接信息');
      return;
    }

    setIsLoading(true);
    try {
      // 转换认证方法格式以匹配Rust枚举
      let authMethod;
      const authType = formData.ssh_config!.auth_method.type;
      
      if (authType === 'password') {
        authMethod = { Password: formData.ssh_config!.password || '' };
      } else if (authType === 'public_key') {
        authMethod = {
          PublicKey: {
            private_key_path: formData.ssh_config!.private_key_path || '',
            passphrase: formData.ssh_config!.private_key_passphrase || null
          }
        };
      } else if (authType === 'agent') {
        authMethod = {
          type: 'agent',
          data: {}
        };
      } else {
        throw new Error('不支持的认证方式');
      }

      const connectionConfig: ConnectionConfig = {
        id: editingConnection?.id || `conn_${Date.now()}`,
        name: formData.name!,
        ssh_config: {
          ...formData.ssh_config as SshConfig,
          auth_method: authMethod
        },
        tunnels: formData.tunnels || [],
        terminal_config: {
          size: null,
          shell: null,
          env_vars: {},
          working_directory: null
        },
        tags: formData.tags || [],
        notes: formData.notes || '',
        created_at: editingConnection?.created_at || new Date().toISOString(),
        last_used_at: editingConnection?.last_used_at,
        use_count: editingConnection?.use_count || 0
      };

      // 调用后端保存连接配置
      await invoke('save_connection_config', { config: connectionConfig });

      // 保存成功后重新加载连接列表以确保数据一致性
      try {
        console.log('连接配置保存成功，重新加载连接列表...');
        const updatedConnections = await invoke('get_saved_connections') as ConnectionConfig[];
        console.log('重新加载的连接数量:', updatedConnections.length);
        console.log('重新加载的连接列表:', updatedConnections.map(c => ({ id: c.id, name: c.name })));
        setConnections(updatedConnections || []);
        console.log('连接列表已更新');
      } catch (error) {
        console.error('重新加载连接列表失败:', error);
        // 如果重新加载失败，仍然更新本地状态作为备选方案
        if (editingConnection) {
          updateConnection(connectionConfig.id, connectionConfig);
        } else {
          addConnection(connectionConfig);
        }
      }

      if (editingConnection) {
        toast.success('连接配置已更新');
      } else {
        toast.success('连接配置已保存');
      }

      handleCloseDialog();
    } catch (error) {
      console.error('Failed to save connection:', error);
      const errorMessage = error instanceof Error ? error.message : (typeof error === 'string' ? error : '未知错误');
      toast.error('保存连接配置失败: ' + errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  // 删除连接配置
  const handleDeleteConnection = async (connectionId: string) => {
    if (!confirm('确定要删除这个连接配置吗？')) {
      return;
    }

    try {
      await invoke('delete_connection_config', { connectionId });
      removeConnection(connectionId);
      
      // 如果有活动连接，也要断开
      const activeConnection = activeConnections.find(ac => ac.id === connectionId);
      if (activeConnection) {
        await handleDisconnect(connectionId);
      }
      
      toast.success('连接配置已删除');
    } catch (error) {
      console.error('Failed to delete connection:', error);
      const errorMessage = error instanceof Error ? error.message : (typeof error === 'string' ? error : '未知错误');
      toast.error('删除连接配置失败: ' + errorMessage);
    }
  };

  // 连接SSH
  const handleConnect = async (connectionId: string) => {
    const connection = connections.find(c => c.id === connectionId);
    if (!connection) {
      toast.error('连接配置不存在');
      return;
    }

    setIsLoading(true);
    try {
      // 准备认证方法数据，检查保存的认证方法格式
      let authMethodData;
      
      // 检查认证方法是否已经是正确的格式（从保存的配置中读取）
      if (connection.ssh_config.auth_method.Password !== undefined) {
        // 已保存的密码认证格式
        authMethodData = {
          type: 'password',
          data: { password: connection.ssh_config.auth_method.Password }
        };
      } else if (connection.ssh_config.auth_method.PublicKey !== undefined) {
        // 已保存的公钥认证格式
        authMethodData = {
          type: 'public_key',
          data: {
            private_key_path: connection.ssh_config.auth_method.PublicKey.private_key_path,
            passphrase: connection.ssh_config.auth_method.PublicKey.passphrase
          }
        };
      } else if (connection.ssh_config.auth_method === 'Agent' || 
                 (typeof connection.ssh_config.auth_method === 'object' && connection.ssh_config.auth_method.type === 'agent')) {
        // 已保存的Agent认证格式
        authMethodData = {
          type: 'agent',
          data: {}
        };
      } else {
        // 兼容旧格式（type字段格式）
        const authType = connection.ssh_config.auth_method.type;
        if (authType === 'password') {
          authMethodData = {
            type: 'password',
            data: { password: connection.ssh_config.password || '' }
          };
        } else if (authType === 'public_key') {
          authMethodData = {
            type: 'public_key',
            data: {
              private_key_path: connection.ssh_config.private_key_path || '',
              passphrase: connection.ssh_config.private_key_passphrase || null
            }
          };
        } else if (authType === 'agent') {
          authMethodData = {
            type: 'agent',
            data: {}
          };
        } else {
          throw new Error('不支持的认证方式: ' + JSON.stringify(connection.ssh_config.auth_method));
        }
      }

      // 调用后端创建SSH连接
      const sshConnection: SshConnection = await invoke('create_ssh_connection', {
        host: connection.ssh_config.host,
        port: connection.ssh_config.port,
        username: connection.ssh_config.username,
        authMethod: authMethodData
      });

      // 使用后端返回的连接ID，而不是强制使用原来的connectionId
      addActiveConnection(sshConnection);

      // 更新最后使用时间
      updateConnection(connectionId, {
        last_used_at: new Date().toISOString()
      });

      // 连接成功后重新加载连接列表以确保显示最新的连接配置
      try {
        console.log('连接成功，重新加载连接列表...');
        console.log('当前连接列表数量:', connections.length);
        const updatedConnections = await invoke('get_saved_connections') as ConnectionConfig[];
        console.log('重新加载的连接数量:', updatedConnections.length);
        console.log('重新加载的连接列表:', updatedConnections.map(c => ({ id: c.id, name: c.name })));
        setConnections(updatedConnections || []);
        console.log('连接列表已更新');
      } catch (error) {
        console.error('重新加载连接列表失败:', error);
      }

      toast.success(`已连接到 ${connection.name}`);
      
      // 连接成功后自动导航到终端页面，使用后端返回的连接ID
      navigate(`/terminal/${sshConnection.id}`);
    } catch (error) {
      console.error('Failed to connect:', error);
      const errorMessage = error instanceof Error ? error.message : (typeof error === 'string' ? error : '未知错误');
      toast.error('连接失败: ' + errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  // 断开SSH连接
  const handleDisconnect = async (connectionId: string) => {
    try {
      await invoke('disconnect_ssh', { connectionId });
      removeActiveConnection(connectionId);
      toast.success('连接已断开');
    } catch (error) {
      console.error('Failed to disconnect:', error);
      const errorMessage = error instanceof Error ? error.message : (typeof error === 'string' ? error : '未知错误');
      toast.error('断开连接失败: ' + errorMessage);
    }
  };

  // 获取连接状态
  const getConnectionStatus = (connectionId: string) => {
    const activeConnection = activeConnections.find(ac => ac.id === connectionId);
    return activeConnection?.status.status || 'disconnected';
  };

  // 渲染连接状态指示器
  const renderStatusIndicator = (status: string) => {
    const statusConfig = {
      connected: { color: 'success', label: '已连接' },
      connecting: { color: 'warning', label: '连接中' },
      disconnected: { color: 'default', label: '未连接' },
      error: { color: 'error', label: '错误' },
    } as const;

    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.disconnected;
    
    return (
      <Chip
        size="small"
        label={config.label}
        color={config.color}
        variant={status === 'connected' ? 'filled' : 'outlined'}
      />
    );
  };

  return (
    <Box sx={{ p: 3, height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 页面头部 */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="h4" gutterBottom>
          连接管理
        </Typography>
        <Typography variant="body2" color="text.secondary">
          管理SSH连接配置，创建和编辑服务器连接
        </Typography>
      </Box>

      {/* 工具栏 */}
      <Paper sx={{ p: 2, mb: 2 }}>
        <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
          <TextField
            size="small"
            placeholder="搜索连接..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            InputProps={{
              startAdornment: <SearchIcon sx={{ mr: 1, color: 'text.secondary' }} />,
            }}
            sx={{ minWidth: 200 }}
          />
          
          <FormControl size="small" sx={{ minWidth: 120 }}>
            <InputLabel>状态过滤</InputLabel>
            <Select
              value={connectionFilter}
              label="状态过滤"
              onChange={(e) => setConnectionFilter(e.target.value as any)}
            >
              <MenuItem value="all">全部</MenuItem>
              <MenuItem value="connected">已连接</MenuItem>
              <MenuItem value="disconnected">未连接</MenuItem>
            </Select>
          </FormControl>

          <Box sx={{ flexGrow: 1 }} />
          
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={() => handleOpenDialog()}
          >
            新建连接
          </Button>
        </Box>
      </Paper>

      {/* 连接列表 */}
      <Paper sx={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        {filteredConnections.length === 0 ? (
          <Box sx={{ p: 4, textAlign: 'center' }}>
            <ComputerIcon sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
            <Typography variant="h6" color="text.secondary" gutterBottom>
              {connections.length === 0 ? '还没有连接配置' : '没有找到匹配的连接'}
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
              {connections.length === 0 ? '点击上方按钮创建第一个SSH连接配置' : '尝试调整搜索条件或过滤器'}
            </Typography>
            {connections.length === 0 && (
              <Button
                variant="contained"
                startIcon={<AddIcon />}
                onClick={() => handleOpenDialog()}
              >
                创建连接
              </Button>
            )}
          </Box>
        ) : (
          <List sx={{ flex: 1, overflow: 'auto' }}>
            {filteredConnections.map((connection) => {
              const status = getConnectionStatus(connection.id);
              const isConnected = status === 'connected';
              
              return (
                <ListItem
                  key={connection.id}
                  sx={{
                    borderBottom: 1,
                    borderColor: 'divider',
                    '&:hover': {
                      backgroundColor: 'action.hover',
                    },
                  }}
                >
                  <Box sx={{ display: 'flex', alignItems: 'center', mr: 2 }}>
                    {connection.ssh_config.auth_method.type === 'password' ? (
                      <LockIcon color="action" />
                    ) : (
                      <KeyIcon color="action" />
                    )}
                  </Box>
                  
                  <ListItemText
                    primary={
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Typography variant="subtitle1" component="span">
                          {connection.name}
                        </Typography>
                        {renderStatusIndicator(status)}
                      </Box>
                    }
                    secondary={
                      <Box>
                        <Typography variant="body2" color="text.secondary">
                          {connection.ssh_config.username}@{connection.ssh_config.host}:{connection.ssh_config.port}
                        </Typography>
                        {connection.tags.length > 0 && (
                          <Box sx={{ mt: 0.5, display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
                            {connection.tags.map((tag, index) => (
                              <Chip key={index} label={tag} size="small" variant="outlined" />
                            ))}
                          </Box>
                        )}
                        {connection.last_used_at && (
                          <Typography variant="caption" color="text.secondary">
                            最后使用: {new Date(connection.last_used_at).toLocaleString()}
                          </Typography>
                        )}
                      </Box>
                    }
                  />
                  
                  <ListItemSecondaryAction>
                    <Box sx={{ display: 'flex', gap: 1 }}>
                      {isConnected ? (
                        <Tooltip title="断开连接">
                          <IconButton
                            color="error"
                            onClick={() => handleDisconnect(connection.id)}
                            disabled={isLoading}
                          >
                            <DisconnectIcon />
                          </IconButton>
                        </Tooltip>
                      ) : (
                        <Tooltip title="连接">
                          <IconButton
                            color="primary"
                            onClick={() => handleConnect(connection.id)}
                            disabled={isLoading}
                          >
                            {isLoading ? <CircularProgress size={20} /> : <ConnectIcon />}
                          </IconButton>
                        </Tooltip>
                      )}
                      
                      <Tooltip title="编辑">
                        <IconButton
                          onClick={() => handleOpenDialog(connection)}
                          disabled={isLoading}
                        >
                          <EditIcon />
                        </IconButton>
                      </Tooltip>
                      
                      <Tooltip title="删除">
                        <IconButton
                          color="error"
                          onClick={() => handleDeleteConnection(connection.id)}
                          disabled={isLoading || isConnected}
                        >
                          <DeleteIcon />
                        </IconButton>
                      </Tooltip>
                    </Box>
                  </ListItemSecondaryAction>
                </ListItem>
              );
            })}
          </List>
        )}
      </Paper>

      {/* 新建/编辑连接对话框 */}
      <Dialog
        open={isDialogOpen}
        onClose={handleCloseDialog}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          {editingConnection ? '编辑连接' : '新建连接'}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 1, display: 'flex', flexDirection: 'column', gap: 2 }}>
            {/* 基本信息 */}
            <TextField
              label="连接名称"
              value={formData.name || ''}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              fullWidth
              required
            />
            
            <TextField
              label="主机地址"
              value={formData.ssh_config?.host || ''}
              onChange={(e) => setFormData({
                ...formData,
                ssh_config: { ...formData.ssh_config!, host: e.target.value }
              })}
              fullWidth
              required
            />
            
            <Box sx={{ display: 'flex', gap: 2 }}>
              <TextField
                label="端口"
                type="number"
                value={formData.ssh_config?.port || 22}
                onChange={(e) => setFormData({
                  ...formData,
                  ssh_config: { ...formData.ssh_config!, port: parseInt(e.target.value) }
                })}
                sx={{ width: 120 }}
              />
              
              <TextField
                label="用户名"
                value={formData.ssh_config?.username || ''}
                onChange={(e) => setFormData({
                  ...formData,
                  ssh_config: { ...formData.ssh_config!, username: e.target.value }
                })}
                fullWidth
                required
              />
            </Box>

            {/* 认证方式 */}
            <FormControl fullWidth>
              <InputLabel>认证方式</InputLabel>
              <Select
                value={formData.ssh_config?.auth_method.type || 'password'}
                label="认证方式"
                onChange={(e) => setFormData({
                  ...formData,
                  ssh_config: {
                    ...formData.ssh_config!,
                    auth_method: { type: e.target.value as any }
                  }
                })}
              >
                <MenuItem value="password">密码认证</MenuItem>
                <MenuItem value="public_key">公钥认证</MenuItem>
                <MenuItem value="agent">SSH Agent</MenuItem>
              </Select>
            </FormControl>

            {/* 认证信息 */}
            {formData.ssh_config?.auth_method.type === 'password' && (
              <TextField
                label="密码"
                type={showPassword ? 'text' : 'password'}
                value={formData.ssh_config?.password || ''}
                onChange={(e) => setFormData({
                  ...formData,
                  ssh_config: { ...formData.ssh_config!, password: e.target.value }
                })}
                fullWidth
                InputProps={{
                  endAdornment: (
                    <IconButton
                      onClick={() => setShowPassword(!showPassword)}
                      edge="end"
                    >
                      {showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}
                    </IconButton>
                  ),
                }}
              />
            )}

            {formData.ssh_config?.auth_method.type === 'public_key' && (
              <>
                <TextField
                  label="私钥文件路径"
                  value={formData.ssh_config?.private_key_path || ''}
                  onChange={(e) => setFormData({
                    ...formData,
                    ssh_config: { ...formData.ssh_config!, private_key_path: e.target.value }
                  })}
                  fullWidth
                />
                <TextField
                  label="私钥密码（可选）"
                  type={showPrivateKeyPassphrase ? 'text' : 'password'}
                  value={formData.ssh_config?.private_key_passphrase || ''}
                  onChange={(e) => setFormData({
                    ...formData,
                    ssh_config: { ...formData.ssh_config!, private_key_passphrase: e.target.value }
                  })}
                  fullWidth
                  InputProps={{
                    endAdornment: (
                      <IconButton
                        onClick={() => setShowPrivateKeyPassphrase(!showPrivateKeyPassphrase)}
                        edge="end"
                      >
                        {showPrivateKeyPassphrase ? <VisibilityOffIcon /> : <VisibilityIcon />}
                      </IconButton>
                    ),
                  }}
                />
              </>
            )}

            {/* 高级选项 */}
            <Divider sx={{ my: 1 }} />
            <Typography variant="subtitle2">高级选项</Typography>
            
            <Box sx={{ display: 'flex', gap: 2 }}>
              <TextField
                label="连接超时（秒）"
                type="number"
                value={formData.ssh_config?.connect_timeout || 30}
                onChange={(e) => setFormData({
                  ...formData,
                  ssh_config: { ...formData.ssh_config!, connect_timeout: parseInt(e.target.value) }
                })}
                sx={{ width: 150 }}
              />
              
              <TextField
                label="保活间隔（秒）"
                type="number"
                value={formData.ssh_config?.keepalive_interval || 60}
                onChange={(e) => setFormData({
                  ...formData,
                  ssh_config: { ...formData.ssh_config!, keepalive_interval: parseInt(e.target.value) }
                })}
                sx={{ width: 150 }}
              />
            </Box>

            <FormControlLabel
              control={
                <Switch
                  checked={formData.ssh_config?.compression || false}
                  onChange={(e) => setFormData({
                    ...formData,
                    ssh_config: { ...formData.ssh_config!, compression: e.target.checked }
                  })}
                />
              }
              label="启用压缩"
            />

            <TextField
              label="备注"
              multiline
              rows={3}
              value={formData.notes || ''}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
              fullWidth
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>取消</Button>
          <Button
            onClick={handleSaveConnection}
            variant="contained"
            disabled={isLoading}
          >
            {isLoading ? <CircularProgress size={20} /> : '保存'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default ConnectionManager;